import { request } from "@umijs/max";

export type MenuItem = {
  menuId: number;
  parentId: number;
  menuName: string;
  children?: MenuItem[];
  [key: string]: any;
};
const resetData = (list: any[]) => {
  return list.map((item) => ({
    ...item,
    label: item.deptName,
    value: item.deptId,
  }));
}; // deptName->label, deptId->value
function buildDeptTree(data: MenuItem[]): MenuItem[] {
  const map: Record<number, MenuItem> = {};
  const tree: MenuItem[] = [];
  const list = resetData(data);
  // 1️⃣ 初始化 map
  list.forEach((item) => {
    map[item.deptId] = { ...item, children: [] };
  });

  // 2️⃣ 构建父子关系
  list.forEach((item) => {
    const parent = map[item.parentId];
    if (parent) {
      parent.children!.push(map[item.deptId]);
    } else {
      // parentId = 0 或 不存在，说明是根节点
      tree.push(map[item.deptId]);
    }
  });

  // 3️⃣ 清理空 children
  const cleanEmptyChildren = (nodes: MenuItem[]) => {
    nodes.forEach((node) => {
      if (node.children && node.children.length > 0) {
        cleanEmptyChildren(node.children);
      } else {
        node.children = undefined; // 空数组改为 undefined
      }
    });
  };

  cleanEmptyChildren(tree);

  return tree;
}
export { buildDeptTree };
// /system/dept/list
export const getDeptList = (params?: any) => {
  return request("/api/system/dept/list", {
    method: "GET",
    params,
  });
};
// system/menu/list
// /system/dept/100
export const getDept = (id: string | number) => {
  return request(`/api/system/dept/${id}`, {
    method: "GET",
  });
};
